﻿using musicapi.Domain;
using musicapi.Provider;
using musicapi.Utils;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;

namespace musicapi.Controllers
{
    public class MusicApiController : ApiController
    {

        [HttpGet, HttpPost,HttpOptions]
        public JsonResult<List<MergedSong>> getSongList(SearchSong searchSong)
        {
            if (searchSong == null||(searchSong.keyword==null)) {
                return Json<List<MergedSong>>(null);
            }
            LogHelper logHelper = new LogHelper();
            logHelper.WriteLog("搜索关键词：" + searchSong.keyword);
            return Json<List<MergedSong>>(FetchSongList(searchSong));
        }


        private List<MergedSong> FetchSongList(SearchSong searchSong)
        {
            List<Song> noCopyrightsSongs = new List<Song>();
            noCopyrightsSongs.Add(new Song { name = searchSong.keyword  });
            List<MergedSong> mergedSongs = FetchCandidateSongs(noCopyrightsSongs,searchSong.pageIndex,searchSong.pageSize);
            mergedSongs=mergedSongs.Where(a => a.items.Where(b=>!string.IsNullOrEmpty(b.picUrl)&&!string.IsNullOrEmpty(b.url)).Count()>0).ToList();
            return mergedSongs;
        }

        private List<MergedSong> FetchCandidateSongs(List<Song> noCopyrightsSongs, int pageIndex, int pageSize)
        {
            List<MergedSong> mergedSongs = new List<MergedSong>();

            noCopyrightsSongs.ForEach(item =>
            {
                List<MergedSong> songList = MusicProviders.Instance.SearchSong(item.name, pageIndex, pageSize, item.source);
                if (songList != null)
                {
                    mergedSongs.AddRange(songList);
                }
            });
            return mergedSongs;
        }

    }
}